/**
 * SysUserSerivceImpl.java
 * Created at 2016-12-26
 * Created by Tinel
 * Copyright (C) 2015 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.repository.EntityDao;
import com.broadtext.common.service.impl.EntityServiceImpl;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.basic.model.TmCustom;
import com.broadtext.rms.system.model.SysAccountValidity;
import com.broadtext.rms.system.model.SysUser;
import com.broadtext.rms.system.model.VSysUsers;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: SysUserSerivceImpl
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Author: Tinel
 * </p>
 * <p>
 * Date: 2016-12-26
 * </p>
 */
@Service("sysUserService")
public class SysUserSerivceImpl extends EntityServiceImpl<SysUser> implements ISysUserService {
    
    /**
     * 锁定
     */
    private static final String IS_LOCK = "1";
    
    /**
     * 未锁定
     */
    private static final String IS_NOT_LOCK = "0";
    
    /**
     * 
     * <p>Description: 注入用户Dao</p>
     * @param entityDao 用户Dao
     */
    @Autowired
    @Qualifier("sysUserDao")
    public void setEntityDao(EntityDao<SysUser> entityDao) {
        super.entityDao = entityDao;
    }

    /**
     * 
     * <p>Description: 用户管理列表翻页查询</p>
     * @param map 查询条件
     * @param pageBounds 翻页信息
     * @return 查询结果
     * @throws ServiceException 异常
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public EntityPageBean findUsersPageByQuery(Map<String, Object> map, PageBounds pageBounds) throws ServiceException {
        EntityPageBean pb;
        pb = new EntityPageBean();
        try {
            pb = this.entityDao.findEntityPageByProperty(
                "com.broadtext.rms.system.model.VSysUsers.findEntityPageByQuery", map, pageBounds);
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return pb;
    }

    /**
     * 
     * <p>Description: 查询用户绑定信息详情</p>
     * @param id 人员ID
     * @return 详情
     * @throws ServiceException 异常
     */
    @SuppressWarnings("unchecked")
    @Override
    public VSysUsers getUserBindInfo(String eId) throws ServiceException {
        VSysUsers vUser;
        vUser = null;
        List<VSysUsers> list;
        list = new ArrayList<VSysUsers>();
        try {
            list = this.entityDao.findByProperty(
                "com.broadtext.rms.system.model.VSysUsers.findEntityById", eId);
            if (list.size() != 0) {
                vUser = list.get(0);
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return vUser;
    }
    
    
    
    /**
     * 
     * <p>Description: 取消用户绑定</p>
     * @param idArray 用户ID集合
     * @param sysUser 当前操作用户名
     * @return 取消结果
     * @throws ServiceException 异常
     */
    @Override
    public boolean cancelUserBind(String[] idArray, String sysUser) throws ServiceException{
        SysUser user;
        for (String id : idArray) {
            try {
                //删除与该用户关联的角色关联
                this.entityDao.deleteRecord("com.broadtext.rms.system.model.TrUserRole.deleteByUserId", id);
                user = super.findEntityById(id);
                //删除用户（真）
                super.deleteRecord(user);
                //删除账户期限信息
                this.entityDao.deleteRecord("com.broadtext.rms.system.model.VSysUsers.deleteAccountValidity", user.getUserId());
            } catch (DaoException e) {
                throw new ServiceException(e);
            }
        }
        return true;
    }

    /**
     * 
     * <p>Description: 用户锁定</p>
     * @param idArray 用户ID集合
     * @param sysUser 当前操作用户名
     * @return 操作结果
     * @throws ServiceException 异常
     */
    @Override
    public boolean lockUser(String sysUser, String[] idArray) throws ServiceException {
        SysUser user;
        for (String id : idArray) {
            user = super.findEntityById(id);
            user.setIsLock(IS_LOCK);
            user.setUpdateUser(sysUser);
            user.setUpdateDate(new Date());
            super.updateRecord(user);
        }
        return true;
    }

    /**
     * 
     * <p>Description: 用户解除锁定</p>
     * @param idArray 用户ID集合
     * @param sysUser 当前操作用户名
     * @return 操作结果
     * @throws ServiceException 异常
     */
    @Override
    public boolean lockCancel(String sysUser, String[] idArray) throws ServiceException {
        SysUser user;
        for (String id : idArray) {
            user = super.findEntityById(id);
            user.setIsLock(IS_NOT_LOCK);
            user.setUpdateUser(sysUser);
            user.setUpdateDate(new Date());
            super.updateRecord(user);
        }
        return true;
    }

    /**
     * 
     * <p>Description: 检测登录名是否与已有数据冲突</p>
     * @param user 待检测用户信息
     * @return 结果
     * @throws ServiceException 异常
     */
    @SuppressWarnings("unchecked")
    @Override
    public Boolean checkUserNameOk(SysUser user) throws ServiceException {
        Boolean flag;
        flag = false;
        List<SysUser> list;
        try {
            list = this.entityDao.findByProperty("com.broadtext.rms.system.model.SysUser.findUserByName", user);
            if (list.size() == 0) {
                flag = true;
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return flag;
    }

    /**
     * 
     * <p>Description: 查询当前未绑定用户数量</p>
     * @return 查询结果
     * @throws ServiceException 异常
     */
    @Override
    public long getUnbindCount(Map<String,Object> map) throws ServiceException {
        long count;
        count = 0;
        try {
            count = (long) this.entityDao.findByProperty("com.broadtext.rms.system.model.VSysUsers.getUnbindCount", map).get(0);
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return count;
    }
    
    /**
     * 
     * <p>Description: 验证当前登录人账号类型</p>
     * @param userId 用户账号
     * @return 结果集
     * @throws DaoException 异常
     */
    public Map<String, Object> checkUserClass(String userId) throws DaoException {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        SysUser user;
        user = (SysUser) this.entityDao.findById("com.broadtext.rms.system.model.SysUser.checkUserClass", userId);
        if(null != user && "2".equals(user.getUserClass())){
            map.put("flag", "true");
            //获取对应的客户
            TmCustom tc;
            tc = (TmCustom) this.entityDao.findById("com.broadtext.rms.basic.model.TmCustom.getCustomerByUserId", user.getUserId());
            if(null != tc && tc.getPkId() != null){
                map.put("cusId", tc.getPkId());
            }else {
                map.put("flag", "false"); 
            }
        } else {
            map.put("flag", "false");
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 验证当前登录人账号类型</p>
     * @param userId 用户账号
     * @return 结果集
     * @throws DaoException 异常
     */
    public Map<String, Object> getUserClass(String loginName) throws DaoException {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        SysUser user;
        user = (SysUser) this.entityDao.findById("com.broadtext.rms.system.model.SysUser.getUserInfoByLoginName", loginName);
        if(null != user && "2".equals(user.getUserClass())){
            map.put("flag", "true");
            //获取对应的客户
            TmCustom tc;
            tc = (TmCustom) this.entityDao.findById("com.broadtext.rms.basic.model.TmCustom.getCustomerByUserId", user.getUserId());
            if(null != tc && tc.getPkId() != null){
                map.put("cusId", tc.getPkId());
            }else {
                map.put("flag", "false"); 
            }
        } else {
            map.put("flag", "false");
        }
        return map;
    }

    /**
     * 
     * <p>Description: 获取用户账户期限信息</p>
     * @param userId 用户账号
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    @Override
    public VSysUsers getAccountValidityInfo(String id) throws ServiceException {
        VSysUsers vUser;
        vUser = null;
        List<VSysUsers> list;
        list = new ArrayList<VSysUsers>();
        try {
            list = this.entityDao.findByProperty(
                "com.broadtext.rms.system.model.VSysUsers.findEntityByEId", id);
            if (list.size() != 0) {
                vUser = list.get(0);
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return vUser;
    }

    /**
     * 
     * <p>Description: 保存账户期限信息</p>
     * @param account 用户账号期限
     * @return 结果集
     * @throws DaoException 异常
     */
    @Override
    public Boolean saveAccountValidityInfo(SysAccountValidity account) throws ServiceException {
        Boolean flag;
        try {
             flag = this.entityDao.insertRecord("com.broadtext.rms.system.model.VSysUsers.saveAccountValidityInfo", account);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return flag;
    }
    
    /**
     * 
     * <p>Description: 保存账户期限信息</p>
     * @param account 用户账号期限
     * @return 结果集
     * @throws DaoException 异常
     */
    @Override
    public Boolean updateAccountValidityInfo(SysAccountValidity user) throws ServiceException {
        Boolean flag;
        try {
             flag = this.entityDao.insertRecord("com.broadtext.rms.system.model.VSysUsers.updateAccountValidityInfo", user);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return flag;
    }

    /**
     * 
     * <p>Description: 修改账户期限信息 EID</p>
     * @param account 用户账号期限
     * @return 结果集
     * @throws DaoException 异常
     */
    @Override
    public Boolean updateAccountValidityByEId(SysAccountValidity account) throws ServiceException {
        Boolean flag;
        try {
             flag = this.entityDao.insertRecord("com.broadtext.rms.system.model.VSysUsers.updateAccountValidityByEId", account);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return flag;
    }
    
    /**
     * 
     * <p>
     * Description: 根据parentKey获取字典详情
     * </p>
     * 
     * @param parentKey parentKey
     * @return 字典详情
     * @throws DaoException
     */
    @SuppressWarnings({"unchecked"})
    public List<String> findTreeCusIds(String rootId) throws ServiceException {
        List<String> ids = new ArrayList<String>() ;
        List<Map<String,Object>> cusIdList;
        cusIdList = new ArrayList<Map<String,Object>>();
        Map<String, Object> queryMap;
        queryMap = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(rootId)){
            queryMap.put("rootId", rootId);
        }
        try {
            cusIdList = this.entityDao.findByProperty("com.broadtext.rms.basic.model.TmCustom.findTreeCusIds", queryMap);
            for (Map<String,Object> map : cusIdList) {
                ids.add(map.get("PK_ID")+"");
            }
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return ids;
    }

    /** (non-Javadoc)
     * <p>Title: getRoleOptions</p>
     * <p>Description: </p>
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.ISysUserService#getRoleOptions()
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Object> getRoleOptions(String isCustomer) throws ServiceException {
        try {
            return this.entityDao.findByProperty(
                "com.broadtext.rms.system.model.VSysUsers.getRoleOptions", isCustomer);
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
    }

    /** (non-Javadoc)
     * <p>Title: saveUserRole</p>
     * <p>Description: </p>
     * @param userId
     * @param roleId
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.ISysUserService#saveUserRole(java.lang.String, java.lang.String)
     */
    @Override
    public boolean saveUserRole(String userId, String roleId) throws ServiceException {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", userId);
        paramMap.put("roleId", roleId);
        paramMap.put("pkId", UUIDUtils.getUUID());
        try {
            return this.entityDao.insertRecord("com.broadtext.rms.system.model.VSysUsers.saveUserRole", paramMap);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /** (non-Javadoc)
     * <p>Title: getCustomerRole</p>
     * <p>Description: </p>
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.ISysUserService#getCustomerRole()
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getCustomerRole() throws ServiceException {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        try {
            list = this.entityDao.findByProperty("com.broadtext.rms.system.model.VSysUsers.getCustomerRole", null);
        } catch (DaoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }

    /** (non-Javadoc)
     * <p>Title: getQueryParams</p>
     * <p>Description: 根据传入的登录名返回查询条件map</p>
     * @param loginName
     * @return
     * @see com.broadtext.rms.system.service.ISysUserService#getQueryParams(java.lang.String)
     */
    @Override
    public Map<String, Object> getQueryParams(String loginName) {
        Map<String, Object> params = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(loginName)) {
            try {
                Map<String, Object> checkMap = this.getUserClass(loginName);
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    params.put("cusId", checkMap.get("cusId"));
                }
            } catch (DaoException e) {
                e.printStackTrace();
            }
            
        }
        return params;
    }

    /** (non-Javadoc)
     * <p>Title: getCustomerId</p>
     * <p>Description: </p>
     * @param loginName
     * @return
     * @see com.broadtext.rms.system.service.ISysUserService#getCustomerId(java.lang.String)
     */
    @Override
    public String getCustomerId(String loginName) {
        String customerId = null;
        if(StringUtils.isNotBlank(loginName)) {
            try {
                Map<String, Object> checkMap = this.getUserClass(loginName);
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    customerId = String.valueOf(checkMap.get("cusId"));
                }
            } catch (DaoException e) {
                e.printStackTrace();
            }
            
        }
        return customerId;
    }
    
    
    
}
